/**
 * Created by Administrator on 2017/6/26.
 */

let schedule = require('node-schedule');
let publicDao = require('../mysql/publicDao.js');
let advanceDao = require('../mysql/advanceDao.js');
let variable = require('../data/variable.js');
let log = require('../util/log.js');
let bluedSDK = require('../util/bluedSDK.js');
let msg = require('../util/msg.js');
let file = require('../util/file.js');
let mem = require('../util/mem.js');
let util = require('../util/util.js');
let gameData = require('../util/gameData.js');
require('../util/prototype.js');
let call = require('./call.js');


let cron = module.exports;

cron.init = function () {
    publicDao.init().table('user').values('gameId', 0).update(function (err, res) {
    });
    publicDao.init().table('robot').values('gameId', 0).update(function (err, res) {
        //log.p('所有人的房间都重置了');
        if (err !== null) {
            return false;
        }
        cronRun();
    });
    gameData.watch();


    //let access_tokenS = '0af78309-5a719dd46b3094-50362138-caa04230';
    //let param = [];
    //for (let i in gameData.d.goods) {
    //    param.push(gameData.d.goods[i]);
    //}
    //bluedSDK.sync(access_tokenS, param, function (result) {
    //    console.log('bluedSDK.goods.sync', result);
    //});
};

function cronRun() {
    // 建立一个时间循环的默认规则
    //let rule = new schedule.RecurrenceRule();
    // 增加一个每秒执行的内容
    //let times = [];
    //for (let i = 1; i < 60; i++) {
    //    times.push(i);
    //}
    //rule.second = times;

    // 刷新机器人
    robotRefresh();

    // 每5秒的动作
    schedule.scheduleJob('*/5 * * * * *', function () {
        robotApply();
        gamePraiseTimeout();
    });

    // 每分的动作
    schedule.scheduleJob('0 * * * * *', function () {
        // 刷新机器人
        robotRefresh();
        // 删除过期房间
        deleteRoom();
    });

    // 每5分的动作
    schedule.scheduleJob('0 */5 * * * *', function () {
        addLog();
    });
}

/**
 * 刷新机器人
 * @returns {boolean}
 */
function robotRefresh() {
    if (!gameData.d.config.robotTurnOn) {
        return false;
    }

    let hours = new Date().getHours();
    publicDao.init().table('robot').wheres('gameId', '=', 0)
        .wheres('onlineTime', '<', hours)
        .wheres('offlineTime', '>', hours)
        .orderRand().get(function (err, res) {
        if (err !== null) {
            return false;
        }
        if (res.length == 0) {
            return false;
        }
        let j = 0;
        mem.robots = {};
        for (let i in res) {
            if (!mem.robots[res[i].gameLv]) {
                mem.robots[res[i].gameLv] = [];
            }
            mem.robots[res[i].gameLv].push(res[i]);
            j++;
        }
        //log.d('刷新了' + j + '个机器人');
    });
    return true;
}


function robotApply() {
    if (mem.robotApply.length <= 0) {
        return false;
    }
    let _ApplyIds = [];
    for (let i in mem.robotApply) {
        let apply = mem.robotApply[i];
        let keys = util.getRandItemsInArray(Object.keys(mem.robots[apply.lv]), 2);
        let ar = [];
        let kk = 0;
        for (let j in keys) {
            ar.push(mem.robots[apply.lv][keys[j]]);
        }
        for (let j in keys) {
            mem.robots[apply.lv].splice(keys[j] - kk, 1);
            kk++;
        }
        apply.cb(ar);
        _ApplyIds.push(i);
    }
    let k = 0;
    for (let i in _ApplyIds) {
        mem.robotApply.splice(_ApplyIds[i] - k, 1);
        k++;
    }
    _ApplyIds = null;
    k = null;
}

/**
 * 删除过期的点赞缓存
 */
function gamePraiseTimeout() {
    let nowTime = Date.now();
    for (let i in mem.gamePraisePlayers) {
        if (mem.gamePraisePlayers[i].endTime > nowTime) {
            continue;
        }
        delete mem.gamePraisePlayers[i];
    }
}

/**
 * 写入在线人数和游戏局数的log
 * @returns {boolean}
 */
function addLog() {
    let date = (new Date()).Format('hh:mm');
    let online = Object.keys(mem.sockets).length;
    let gameLv = [];
    for (let i in gameData.d.gameLv) {
        gameLv[gameData.d.gameLv[i].lv] = 0;
    }
    for (let i in mem.gameLists) {
        gameLv[mem.gameLists[i].lv]++;
    }
    file.append(variable.path.online, date + ',' + online + "\n");
    file.append(variable.path.games, date + ',' + gameLv.join(',') + "\n");
    return true;
}


function deleteRoom() {
    let now = Date.now();
    let gameDuration = (gameData.d.config.gameDuration * 1000);
    for (let i in mem.gameLists) {
        let game = mem.gameLists[i];
        if (now - game.createTime < gameDuration) {
            continue;
        }

        call.gameLists.delGame(i);
        call.gameLists.delRecruit(i);
        log.p('timeout kill room in dc', i);
    }
}